package com.example.demo.service;

import com.example.demo.SpringContextUtil;
import com.example.demo.dao.Creation;
import com.example.demo.dao.BaseDao;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class BaseService<T, D> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public T get(String id){
        return getBaseDao().get(id);
    }

    public List<T> search(Creation... creations){
        return getBaseDao().search(creations);
    }

    public List<Map<String, Object>> grid(Creation ... creations){
        return getBaseDao().grid(creations);
    }

    public void insert(T t){
        try {
            String id = (String)PropertyUtils.getProperty(t, "id");
            if(StringUtils.isEmpty(id)){
                PropertyUtils.setProperty(t, "id", UUID.randomUUID().toString());
            }
        } catch (Exception e) {
            logger.error("{}", e);
        }
        getBaseDao().insert(t);
    }

    public void batchInsert(List<T> list){
        getBaseDao().batchInsert(list);
    }

    public void update(T t){
        getBaseDao().update(t);
    }

    public void delete(String id){
        getBaseDao().delete(id);
    }

    public void deleteByCreations(Creation ... creations){
        getBaseDao().deleteByCreations(creations);
    }

    private Class getGenericClass(){
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return  (Class)params[1];
    }

    private BaseDao<T> getBaseDao(){
        return (BaseDao)SpringContextUtil.getBean(getGenericClass());
    }
}
